<template>
  <div id="addPicturePage">
    <a-card :bordered="false" class="form-container">
      <h2 class="title">
        {{ route.query?.id ? '修改图片' : '创建图片' }}
      </h2>

      <a-typography-paragraph v-if="spaceId" type="secondary">
        保存至空间：<a :href="`/space/${spaceId}`" target="_blank">{{ spaceId }}</a>
      </a-typography-paragraph>


      <!-- 选择上传方式 -->
      <a-tabs v-model:activeKey="uploadType">
        <a-tab-pane key="file" tab="文件上传">
          <PictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
        </a-tab-pane>
        <a-tab-pane key="url" tab="URL 上传" force-render>
          <UrlPictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
        </a-tab-pane>
      </a-tabs>

      <div style="display: flex; justify-content: center; align-items: center; gap: 16px;">
        <a-button :icon="h(EditOutlined)" @click="doEditPicture">
          编辑图片
        </a-button>
        <a-button type="primary" ghost :icon="h(FullscreenOutlined)" @click="doImagePainting">
          AI 扩图
        </a-button>
        <a-button type="primary" ghost :icon="h(InteractionFilled)" @click="doImageReStyle">
          AI 人像风格重塑
        </a-button>
      </div>



      <!-- 表单 -->
      <a-form v-if="picture" layout="vertical" :model="pictureForm" @finish="handleSubmit">
        <a-form-item label="名称" name="name">
          <a-input v-model:value="pictureForm.name" placeholder="请输入名称" class="form-input" />
        </a-form-item>

        <a-form-item label="简介" name="introduction">
          <a-textarea
            v-model:value="pictureForm.introduction"
            placeholder="请输入简介"
            :rows="2"
            autoSize
            allowClear
            class="form-textarea"
          />
        </a-form-item>

        <a-form-item label="分类" name="category">
          <a-auto-complete
            v-model:value="pictureForm.category"
            :options="categoryOptions"
            placeholder="请输入分类"
            allowClear
            class="form-input"
          />
        </a-form-item>

        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="pictureForm.tags"
            :options="tagOptions"
            mode="tags"
            placeholder="请输入标签"
            allowClear
            class="form-input"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" class="submit-button">
            {{ route.query?.id ? '保存修改' : '创建图片' }}
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <div v-if="picture" class="edit-bar">
      <image-corpper
        ref="imageCropperRef"
        :imageUrl="picture?.url"
        :picture="picture"
        :spaceId="spaceId"
        :space="space"
        :onSuccess="onSuccess"
      />
      <ImageOutPainting
        ref="imageOutPaintingRef"
        :picture="picture"
        :spaceId="spaceId"
        :onSuccess="onImageOutPaintingSuccess"
      />
      <ImageRestyle
        ref="imageReStyleRef"
        :picture="picture"
        :spaceId="spaceId"
        :onSuccess="onImageReStyleSuccess"
      />
    </div>

  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed, h, watchEffect } from 'vue'
import PictureUpload from '@/components/PictureUpload.vue'
import { useRoute, useRouter } from 'vue-router'
import {
  editPictureUsingPost,
  getPictureVoByIdUsingGet,
  listPictureTagCategoryUsingGet,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import UrlPictureUpload from '@/components/UrlPictureUpload.vue'
import { EditOutlined,FullscreenOutlined,InteractionFilled } from '@ant-design/icons-vue'
import ImageCorpper from '@/components/imageCorpper.vue'
import ImageOutPainting from '@/components/imageOutPainting.vue'
import ImageRestyle from '@/components/imageRestyle.vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController.ts'

// 图片编辑弹窗引用
const imageCropperRef = ref()

// 编辑图片
const doEditPicture = () => {
  if (imageCropperRef.value) {
    imageCropperRef.value.openModal()
  }
}

// 编辑成功事件
const onCropSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

const picture = ref<API.PictureVO>()
const pictureForm = reactive<API.PictureEditRequest>({
  name: '',
  introduction: '',
  category: '',
  tags: []
})
const uploadType = ref<'file' | 'url'>('file')

const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  // 回填表单数据
  pictureForm.name = newPicture.name
}

const router = useRouter()

// 空间 id
const spaceId = computed(() => {
  return route.query?.spaceId
})


/**
 * 提交表单
 */
const handleSubmit = async (values: any) => {
  const pictureId = picture.value?.id
  if (!pictureId) {
    return
  }

  const res = await editPictureUsingPost({
    id: pictureId,
    spaceId: spaceId.value,
    ...values,
  })

  if (res.data.code === 0 && res.data.data) {
    message.success('创建成功 🎉')

    // 检查用户是否是管理员
    if (isAdmin.value) {
      router.push({
        path: `/picture/${pictureId}`,
      })
    }
  } else {
    message.error('创建失败，' + res.data.message)
  }
}

/**
 * 判断用户是否是管理员的计算属性
 */
const user = useLoginUserStore().loginUser
const isAdmin = computed(() => user.userRole === 'admin')

const categoryOptions = ref<{ value: string; label: string }[]>([])
const tagOptions = ref<{ value: string; label: string }[]>([])

/**
 * 获取标签和分类选项
 */
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => ({
      value: data,
      label: data,
    }))
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => ({
      value: data,
      label: data,
    }))
  } else {
    message.error('加载选项失败，' + res.data.message)
  }
}

onMounted(() => {
  getTagCategoryOptions()
})

const route = useRoute()

/**
 * 获取已有的图片信息
 */
const getOldPicture = async () => {
  const id = route.query?.id
  if (!id) return; // 防止无效请求

  const res = await getPictureVoByIdUsingGet({ id })
  if (res.data.code === 0 && res.data.data) {
    const data = res.data.data
    picture.value = data
    Object.assign(pictureForm, data) // 回填表单数据
  }
}

onMounted(() => {
  getOldPicture()
})

// AI 扩图弹窗引用
const imageOutPaintingRef = ref()

// AI 人像风格重塑弹窗引用
const imageReStyleRef = ref()

// AI 扩图
const doImagePainting = () => {
  if (imageOutPaintingRef.value) {
    imageOutPaintingRef.value.openModal()
  }
}

// AI 人像风格重塑
const doImageReStyle = () => {
  if (imageReStyleRef.value) {
    imageReStyleRef.value.openModal()
  }
}

// 编辑成功事件
const onImageOutPaintingSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

// 编辑成功事件
const onImageReStyleSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

const space = ref<API.SpaceVO>()

// 获取空间信息
const fetchSpace = async () => {
  // 获取数据
  if (spaceId.value) {
    const res = await getSpaceVoByIdUsingGet({
      id: spaceId.value,
    })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    }
  }
}

watchEffect(() => {
  fetchSpace()
})

</script>

<style scoped>
/* 全局背景美化，增加高斯模糊 */
#addPicturePage {
  max-width: 800px;
  margin: 40px auto;
  padding: 20px;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease-in-out;
}

/* 卡片容器优化 */
.form-container {
  padding: 32px;
  border-radius: 16px;
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.1);
  background: linear-gradient(to right, #ffffff, #f9f9f9);
  transition: all 0.3s ease-in-out;
}
.form-container:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

/* 标题优化，增加动画 */
.title {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 30px;
  text-transform: uppercase;
  transition: all 0.3s ease-in-out;
}
.title:hover {
  color: #1890ff;
  letter-spacing: 1px;
}

/* 输入框美化 */
.form-input,
.form-textarea {
  border-radius: 10px;
  padding: 10px;
  font-size: 16px;
  transition: all 0.3s;
  border: 1px solid #d9d9d9;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
}
.form-input:focus,
.form-textarea:focus {
  border-color: #1890ff !important;
  box-shadow: 0 0 12px rgba(24, 144, 255, 0.3);
  transform: scale(1.02);
}

/* 提交按钮美化 */
.submit-button {
  width: 100%;
  background: linear-gradient(135deg, #1890ff, #40a9ff);
  border-radius: 12px;
  height: 50px;
  font-size: 18px;
  font-weight: bold;
  color: #fff;
  transition: all 0.3s;
  border: none;
  text-transform: uppercase;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.submit-button:hover {
  background: linear-gradient(135deg, #40a9ff, #69c0ff);
  transform: translateY(-3px);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.2);
}

/* Tabs 样式优化 */
:deep(.ant-tabs-tab) {
  font-size: 16px;
  font-weight: bold;
  transition: color 0.3s, transform 0.3s;
}
:deep(.ant-tabs-tab-active) {
  color: #1890ff !important;
  transform: scale(1.1);
}

</style>
